package com.wyp.didishige.activity;

import android.Manifest;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.ImageView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.umeng.analytics.MobclickAgent;
import com.umeng.update.UmengUpdateAgent;
import com.wyp.didishige.MyApplication;
import com.wyp.didishige.activity.login.LoginActivity;
import com.wyp.didishige.config.Config;
import com.wyp.didishige.db.NewCommentManager;
import com.wyp.didishige.fragment.DiscoverFragment;
import com.wyp.didishige.fragment.NearFragment;
import com.wyp.didishige.fragment.RecentFragment;
import com.wyp.didishige.fragment.SettingsFragment;
import com.wyp.didishige.utils.IntentUtil;
import com.wyp.didishige.utils.PreferenceHelper;
import com.wyp.didishige.wiget.ChangeColorIconWithTextView;
import com.wyp.didishige.R;
import com.wyp.didishige.model.User;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import cn.bmob.newim.BmobIM;
import cn.bmob.newim.event.MessageEvent;
import cn.bmob.newim.listener.ConnectListener;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.exception.BmobException;

/**
 * 首页
 */
@SuppressWarnings("ALL")
public class MainActivity extends BaseActivity
        implements View.OnClickListener, ViewPager.OnPageChangeListener {
    public final static int MSG_REFRESH_DYNAMIC_CODE = 0;
    public final static String MSG_REFRESH_CODE = "MSG_REFRESH_CODE";

    FragmentManager fragmentManager;
    BmobGeoPoint bmobGeoPoint;
    User user;
    private ViewPager mViewPager;
    private List<Fragment> mTabs = new ArrayList<Fragment>();
    private FragmentPagerAdapter mAdapter;

    private DiscoverFragment discoverFragment;
    private RecentFragment recentFragment;
    private NearFragment nearFragment;
    private SettingsFragment settingFragment;
    //    ImageView iv_recent_tips, iv_contact_tips;//消息提示
    private List<ChangeColorIconWithTextView> mTabIndicator = new ArrayList<ChangeColorIconWithTextView>();
    private NewBroadcastReceiver newBroadcastReceiver=new NewBroadcastReceiver();
    private ImageView msgTips = null;
    private ImageView meTips = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setOverflowShowingAlways();
        actionBar = getSupportActionBar();
        assert actionBar != null;
        actionBar.setTitle("首页");
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);

        user = BmobUser.getCurrentUser(this,User.class);
        getLocation();
        connectIM();
        fragmentManager = getSupportFragmentManager();
        if (user != null) {
            user.setLastLogin(System.currentTimeMillis());
            user.update(this);
        } else {
            IntentUtil.start_activity(this, LoginActivity.class);
        }

        mViewPager = (ViewPager) findViewById(R.id.id_viewpager);
        IntentFilter filter=new IntentFilter();
        filter.addAction(MSG_REFRESH_CODE);
        registerReceiver(newBroadcastReceiver,filter);
        initTab();
    }

    private void applyRight(){
        // 检查activity是否有写日程的权限
        int intpermissionCheck= ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    }
    private void connectIM(){
        if (user!=null){
            BmobIM.getInstance().connect(user.getObjectId(), new ConnectListener() {
                @Override
                public void done(String s, BmobException e) {

                }
            });
        }
    }
    private void initTabIndicator() {
        ChangeColorIconWithTextView one = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_one);
        ChangeColorIconWithTextView two = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_two);
        ChangeColorIconWithTextView three = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_three);
        ChangeColorIconWithTextView four = (ChangeColorIconWithTextView) findViewById(R.id.id_indicator_four);
        msgTips = (ImageView) findViewById(R.id.msgTips);
        meTips = (ImageView) findViewById(R.id.meTips);

        mTabIndicator.add(one);
        mTabIndicator.add(two);
        mTabIndicator.add(three);
        mTabIndicator.add(four);

        assert one != null;
        one.setOnClickListener(this);
        assert two != null;
        two.setOnClickListener(this);
        assert three != null;
        three.setOnClickListener(this);
        assert four != null;
        four.setOnClickListener(this);

        one.setIconAlpha(1.0f);
    }

    private void initTab() {
        discoverFragment = new DiscoverFragment();


        recentFragment = new RecentFragment();

        settingFragment = new SettingsFragment();
        if (PreferenceHelper.readBoolean(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false)) {
            nearFragment = NearFragment.newInstance(false);
            mTabs.add(nearFragment);
            mTabs.add(discoverFragment);
        } else {
            nearFragment = new NearFragment();
            mTabs.add(discoverFragment);
            mTabs.add(nearFragment);
        }

        mTabs.add(recentFragment);
        mTabs.add(settingFragment);

        mAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {

            @Override
            public int getCount() {
                return mTabs.size();
            }

            @Override
            public Fragment getItem(int arg0) {
                return mTabs.get(arg0);
            }
        };

        initTabIndicator();

        mViewPager.setAdapter(mAdapter);
        mViewPager.setOffscreenPageLimit(4);
        mViewPager.setOnPageChangeListener(this);

    }

    @Override
    public void onPageSelected(int postion) {
        supportInvalidateOptionsMenu();
        switch (postion){
            case 0:
                actionBar.setTitle("首页");
                break;
            case 1:
                actionBar.setTitle("发现");
                break;
            case 2:
                actionBar.setTitle("消息");
                break;
            case 3:
                actionBar.setTitle("我的");
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset,
                               int positionOffsetPixels) {
        if (positionOffset > 0) {
            ChangeColorIconWithTextView left = mTabIndicator.get(position);
            ChangeColorIconWithTextView right = mTabIndicator.get(position + 1);

            left.setIconAlpha(1 - positionOffset);
            right.setIconAlpha(positionOffset);
        }

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onClick(View v) {

        resetOtherTabs();

        switch (v.getId()) {
            case R.id.id_indicator_one:
                if (PreferenceHelper.readBoolean(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false)) {
                    MobclickAgent.onEvent(this, "main_near_click");
                } else {
                    MobclickAgent.onEvent(this, "main_discovr_click");
                }

                mTabIndicator.get(0).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(0, false);
                break;
            case R.id.id_indicator_two:

                if (PreferenceHelper.readBoolean(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false)) {
                    MobclickAgent.onEvent(this, "main_discovr_click");
                } else {
                    MobclickAgent.onEvent(this, "main_near_click");
                }

                mTabIndicator.get(1).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(1, false);
                break;
            case R.id.id_indicator_three:
                MobclickAgent.onEvent(this, "main_recent_click");
                mTabIndicator.get(2).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(2, false);
                break;
            case R.id.id_indicator_four:
                MobclickAgent.onEvent(this, "main_setting_click");
                mTabIndicator.get(3).setIconAlpha(1.0f);
                mViewPager.setCurrentItem(3, false);
                break;

        }

    }

    /**
     * 重置其他的Tab
     */
    private void resetOtherTabs() {
        for (int i = 0; i < mTabIndicator.size(); i++) {
            mTabIndicator.get(i).setIconAlpha(0);
        }
    }

    /**
     * 新消息广播接收者
     */
    private class NewBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //刷新界面
            refreshNewMsg(null);
            // 记得把广播给终结掉
            abortBroadcast();
        }
    }

    /**
     * 刷新界面
     */
    private void refreshNewMsg(MessageEvent message) {
        // 声音提示
        boolean isAllow = MyApplication.getInstance().getSpUtil().isAllowVoice();
        if (isAllow) {
            MyApplication.getInstance().getMediaPlayer().start();
        }

        if (mViewPager.getCurrentItem() == 2) {
            //当前页面如果为会话页面，刷新此页面
            if (recentFragment != null) {
                recentFragment.refresh();
            }
        }
        msgTips.setVisibility(View.VISIBLE);

        if(NewCommentManager.getInstance(this).hasNewCommentNotify()){
            meTips.setVisibility(View.VISIBLE);
        }else{
            meTips.setVisibility(View.GONE);
        }
        if (settingFragment != null) {
            settingFragment.refreshTips();
        }
    }

    /**
     * 刷新好友请求
     * @param message
     */
//    private void refreshInvite(BmobInvitation message) {
//        boolean isAllow = MyApplication.getInstance().getSpUtil().isAllowVoice();
//        if (isAllow) {
//            MyApplication.getInstance().getMediaPlayer().start();
//        }
//        msgTips.setVisibility(View.VISIBLE);
//        //同时提醒通知
//        String tickerText = "有窝友请求添加好友";
//        boolean isAllowVibrate = MyApplication.getInstance().getSpUtil().isAllowVibrate();
//        BmobNotifyManager.getInstance(this).showNotify(isAllow, isAllowVibrate, R.drawable.ic_launcher,
//                tickerText, "窝友", tickerText.toString(), NewFriendActivity.class);
//    }

    /**
     * 隐藏tips
     */
    public void hiddenMsgTips() {
        msgTips.setVisibility(View.GONE);
    }

    public void refreshPoint(BmobGeoPoint point) {
        bmobGeoPoint = point;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (PreferenceHelper.readBoolean(this, Config.PreferenceHelperfile, Config.USER_SEX_MALE, false)) {
            if (mViewPager.getCurrentItem() == 0) {
                getMenuInflater().inflate(R.menu.menu_nearpeople_activity, menu);
            }
        } else {
            if (mViewPager.getCurrentItem() == 1) {
                getMenuInflater().inflate(R.menu.menu_nearpeople_activity, menu);
            }
        }

        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id) {
            case android.R.id.home:
                break;
            case R.id.logout:
                break;
            case R.id.about:
                break;
            case R.id.action_all:
                MobclickAgent.onEvent(this, "recent_right_top_all_click");
                nearFragment.setSex(null);
                break;
            case R.id.action_female:
                MobclickAgent.onEvent(this, "recent_right_top_female_click");
                nearFragment.setSex(false);
                break;
            case R.id.action_male:
                MobclickAgent.onEvent(this, "recent_right_top_male_click");
                nearFragment.setSex(true);
                break;
            case R.id.action_notification:
                break;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(newBroadcastReceiver);
    }

    long firsttime;

    @Override
    public void onBackPressed() {
//        if (firsttime + 2000 > System.currentTimeMillis()) {
        MobclickAgent.onKillProcess(this);
        finish();
//        } else {
//            ShowToast("再按一次退出程序");
//        }
//        firsttime = System.currentTimeMillis();
    }

    @Override
    public void onResume() {
        super.onResume();
        //小圆点提示
        if (BmobIM.getInstance().getAllUnReadCount()>0) {
            msgTips.setVisibility(View.VISIBLE);
        } else {
            msgTips.setVisibility(View.GONE);
        }

        if(NewCommentManager.getInstance(this).hasNewCommentNotify()){
            meTips.setVisibility(View.VISIBLE);
        }else{
            meTips.setVisibility(View.GONE);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
    }

    private void setOverflowShowingAlways() {
        try {
            // true if a permanent menu key is present, false otherwise.
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            menuKeyField.setAccessible(true);
            menuKeyField.setBoolean(config, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case MSG_REFRESH_DYNAMIC_CODE:
                    discoverFragment.onRefresh();
                    break;
            }
        }
    }
    BmobGeoPoint geoPoint;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    /**
     * 定位
     */
    private void getLocation() {
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
//        option.setScanSpan(2000);
        mLocClient.setLocOption(option);
        mLocClient.start();
    }

    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            if (location != null) {
                reverseGeoCode(location);
                geoPoint = new BmobGeoPoint(location.getLongitude(), location.getLatitude());
            } else {
                // 无定位数据默认北京中心
                double cLat = 39.909230;
                double cLon = 116.397428;
                geoPoint = new BmobGeoPoint(cLon, cLat);
            }

            //更新当前位置
            refreshPoint(geoPoint);


            if (user != null) {
                user.setCity(location.getCity());
                user.setLocation(geoPoint);
                user.update(MainActivity.this);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    private void reverseGeoCode(BDLocation location) {
        GeoCoder geoCoder = GeoCoder.newInstance();
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(new LatLng(location.getLatitude(), location.getLongitude())));
        geoCoder.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
            @Override
            public void onGetGeoCodeResult(GeoCodeResult geoCodeResult) {

            }

            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
                if (null == user) return;
                user.setCity(reverseGeoCodeResult.getAddressDetail().city);
                user.setProvince(reverseGeoCodeResult.getAddressDetail().province);
                user.setDistrict(reverseGeoCodeResult.getAddressDetail().district);
                user.setStreet(reverseGeoCodeResult.getAddressDetail().street);
                user.setStreetNumber(reverseGeoCodeResult.getAddressDetail().streetNumber);
                user.update(MainActivity.this);
            }
        });
    }
}
